package com.itxzh.logindemo.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {

    private static String SECRET = "token!Q@W3e4r";

    /**
     * 生成token
     * @param map  //传入Payload
     * @return 返回token
     */
    public static String getToken(Map<String,String> map){
        JWTCreator.Builder builder = JWT.create();
        builder.withSubject("admin").withIssuedAt(new Date());

        map.forEach((k,v)->{
            builder.withClaim(k,v);	// Payload 有效载荷
        });
        // 设置过期时间 7秒
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND,60*60);
        builder.withExpiresAt(instance.getTime());
        return builder.sign(Algorithm.HMAC256(SECRET));	// 签名
    }

    /**
     * 验证token
     * @param token
     * @return
     */
    public static DecodedJWT verify(String token){
        return JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);  // 如果验证通过，则不会把报错，否则会报错
    }

//    /**
//     * 获取token中payload
//     * @param token
//     * @return
//     */
//    public static DecodedJWT getToken(String token){
//        return JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
//    }

    public static void main(String[] args) {
        HashMap<String, String> map = new HashMap<>();
        map.put("userName", "老张");
        map.put("age", "20");
        String token = JwtUtil.getToken(map);
        System.out.println(token);
        DecodedJWT res = JwtUtil.verify(token);
        System.out.println(res.getClaim("userName").asString());
        System.out.println(res.getClaim("age").asString());
    }

}

